//
//  VideoCache.m
//  封装播放器
//
//  Created by douya on 15/1/26.
//  Copyright (c) 2015年 douya. All rights reserved.
//

#import "VideoCache.h"
#import <UIKit/UIKit.h>
#import "AFNetworking.h"
@implementation VideoCache
static VideoCache *_cache=nil;
//单例类 某个对象只会被创建一次
+(id)shareVideoCache
{
    @synchronized(self)//单例类 也要处理线程同步问题，防止多个线程同时获取这个对象有时会创建多次
    {
        if (_cache==nil)
        {
            _cache=[[VideoCache alloc] init];
        }
        return _cache;
    }
}

//重写alloc方法，为防止别人手动来调用alloc导致创建对象不是单例了
+(id)alloc
{
    @synchronized(self)
    {
        if (_cache==nil)
        {
            _cache=[super alloc];
        }
        return _cache;
    }
}

-(id)init
{
    if ([super init])
    {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(clearMemory) name:UIApplicationDidReceiveMemoryWarningNotification object:nil];
    }
    return self;
}

-(void)clearMemory
{
    NSLog(@"内存警告");
    NSLog(@"总大小  %fM",[self  getSize]);
    
}

//从沙盒中找
-(NSURL *)searchLocalFromSandBox:(NSString *)string
{
    NSString *filePath=[self getFilePath:string];
    
    NSData *data=[NSData dataWithContentsOfFile:filePath];
    if (data==nil)
    {
        return nil;
    }
    else
    {
        NSURL *url=[NSURL fileURLWithPath:filePath];
        return url;
    }
    
    
    
}

//从网络上获取
-(NSURL *)getFromNetworkWithString:(NSString *)string
{
    NSURL *url=[NSURL URLWithString:string];
    //提供异步下载
    dispatch_queue_t queue=dispatch_get_global_queue(0, 0);
    dispatch_async(queue, ^{
        NSURLSessionConfiguration *configuration=[NSURLSessionConfiguration defaultSessionConfiguration];
        AFURLSessionManager *manager=[[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
        NSURL *url=[NSURL URLWithString:string];
        NSURLRequest *request=[NSURLRequest requestWithURL:url];
        
        NSURLSessionDownloadTask *downLoadTask=[manager downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath,NSURLResponse *response){
            
            NSString *directoryPath=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0] stringByAppendingString:@"/videoCaches/"];
            
            NSURL *documentsDirectoryURL=[NSURL fileURLWithPath:directoryPath];
            
            return [documentsDirectoryURL URLByAppendingPathComponent:response.suggestedFilename];
        }completionHandler:^(NSURLResponse *response,NSURL *filePath,NSError *error){
            NSLog(@"File downloaded to:%@",filePath);
            
            //返回主线程
            dispatch_async(dispatch_get_main_queue(), ^
                           {
                               
                           });
            
        }];
        
        [downLoadTask resume];
    });
    
    return url;
    
}
//拼接文件路径
-(NSString *)getFilePath:(NSString *)fileName
{
    NSString *directoryPath=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0] stringByAppendingString:@"/videoCaches"];
    //判断这个文件夹是否存在
    if (![[NSFileManager defaultManager] fileExistsAtPath:directoryPath])
    {
        //如果不存在则创建一个
        [[NSFileManager defaultManager] createDirectoryAtPath:directoryPath withIntermediateDirectories:YES attributes:nil error:nil];
    }
    
    //把地址按照/分割 取最后一个
    NSString *videoHeadName=[[fileName componentsSeparatedByString:@"/"] lastObject];
    
    NSString *filePath=[NSString stringWithFormat:@"%@/%@",directoryPath,videoHeadName];
    
    return filePath;
}
//获取缓存的总大小
-(float)getSize
{
    NSString *directoryPath=[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
    //获取文件夹的枚举器
    NSDirectoryEnumerator *enumerator=[[NSFileManager defaultManager] enumeratorAtPath:directoryPath];
    
    long long size=0;
    //从文件夹中的第一个文件开始读，每次读一个文件，读到一个文件时，我们获取这个文件的大小
    while ([enumerator nextObject])
    {
        size += enumerator.fileAttributes.fileSize;
    }
    NSLog(@"%lld",size);
    
    float floatSize=size/1000.0/1000.0;
    return floatSize;
    
}

@end
